package edu.suda.cxtz.service.impl;

import com.github.dozermapper.core.Mapper;
import edu.suda.cxtz.entity.Dict;
import edu.suda.cxtz.repository.DictRepository;
import edu.suda.cxtz.entity.dto.DictDto;
import edu.suda.cxtz.entity.dto.DictQueryCriteria;
import edu.suda.cxtz.service.DictService;
import edu.suda.cxtz.utils.DtoEntityUtil;
import edu.suda.cxtz.utils.QueryHelp;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class DictServiceImpl implements DictService {

    private final DictRepository dictRepository;
    private final DtoEntityUtil mapper;


    @Override
    public List<DictDto> queryAll(DictQueryCriteria dict) {
        List<Dict> list = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb));
        return mapper.trans(list, DictDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Dict resources) {
        dictRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Dict resources) {
        Dict dict = dictRepository.findById(resources.getId()).orElseGet(Dict::new);
        if(ObjectUtils.isEmpty(dict.getId())) {
            throw new RuntimeException("数据不存在");
        }
        dict.setName(resources.getName());
        dict.setDescription(resources.getDescription());
        dictRepository.save(dict);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        List<Dict> dicts = dictRepository.findByIdIn(ids);
        dictRepository.deleteByIdIn(ids);
    }

}